package cores

import (
	"github.com/asaskevich/govalidator"
	log "github.com/sirupsen/logrus"
	"simulationFulu/dao"
	"simulationFulu/models"
	"simulationFulu/utils"
	"strconv"
	"time"
)

// 创建一张卡券
func NewCard() *models.Card {
	e := new(models.Card)
	e.CardDeadline = time.Now().AddDate(0, 0, 20)
	e.CardNumber = "321"
	e.CardPwd = "123"
	dao.CardAdd(e)
	return e
}

// 创建一批卡券
func NewCards(count int, orderId int64, hasCardNo, hasCardPwd, hasCardUrl bool) []models.Card {
	cards := make([]models.Card, count)
	numDataSeed := ""
	if hasCardNo {
		numDataSeed = strconv.FormatInt(time.Now().Unix(), 10)
	}
	secret := models.GetConfig().Secret
	log.Info("Secret:", secret)
	bs := GetAesKey(secret)
	for i := 0; i < count; i++ {
		var card models.Card
		card.CardDeadline = time.Now().AddDate(0, 0, 20)
		card.OrderId = orderId
		// 卡号
		if len(numDataSeed) > 0 {
			data := numDataSeed + strconv.Itoa(i)
			card.RawCardNumber = data
			res := utils.ECBEncWithPKCS7([]byte(data), bs)
			card.CardNumber = res
		} else {
			card.RawCardNumber = "无卡号"
			card.CardNumber = utils.ECBEncWithPKCS7([]byte("无卡号"), bs)
		}
		// 卡密
		if hasCardPwd {
			if hasCardUrl {
				url := "http://123456"
				card.RawCardPwd = url
				card.CardPwd = utils.ECBEncWithPKCS7([]byte(url), bs)
			} else {
				pwd := "123456"
				card.RawCardPwd = pwd
				card.CardPwd = utils.ECBEncWithPKCS7([]byte(pwd), bs)
			}
		}
		cards[i] = card
	}
	dao.CardBulkAdd(cards)
	return cards
}

func GetAesKey(key string) []byte {
	if len(key) < 32 {
		key = govalidator.PadRight(key, "0", 32)
	} else {
		key = key[:32]
	}
	return []byte(key)
}
